package com.example.activitys;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.example.tracontroller.R;

//
public class RecordListItem extends RelativeLayout {

	public int mRecordId;
	public boolean mSelected;

	private boolean mAllowBatch;
	private RecordListAdapter mAdapter;
	private boolean mDownEvent;
	private boolean mCachedViewPositions;
	private int mCheckRight;
	private int mStarLeft;

	private final static float CHECKMARK_PAD = 10.0F;

	public RecordListItem(Context context) {
		super(context);
	}

	public RecordListItem(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public RecordListItem(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void bindViewInit(RecordListAdapter adapter, boolean allowBatch) {
		mAdapter = adapter;
		mAllowBatch = allowBatch;
		mCachedViewPositions = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		boolean handled = false;
		int touchX = (int) event.getX();

		if (!mCachedViewPositions) {
			float paddingScale = getContext().getResources()
					.getDisplayMetrics().density;
			int checkPadding = (int) ((CHECKMARK_PAD * paddingScale) + 0.5);
			mCheckRight = findViewById(R.id.selected).getRight() + checkPadding;
			mCachedViewPositions = true;
		}

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mDownEvent = true;
			if ((mAllowBatch && touchX < mCheckRight) || touchX > mStarLeft) {
				handled = true;
			}
			break;

		case MotionEvent.ACTION_CANCEL:
			mDownEvent = false;
			break;

		case MotionEvent.ACTION_UP:
			if (mDownEvent) {
				if (mAllowBatch && touchX < mCheckRight) {
					mSelected = !mSelected;
//					mAdapter.updateSelected(this, mSelected);
					handled = true;
				}
			}
			break;
		}

		if (handled) {
			postInvalidate();
		} else {
			handled = super.onTouchEvent(event);
		}

		return handled;
	}
}
